<?php


namespace app\api\controller;

use app\api\model\MeetModel;
use app\api\model\MeetNoticeModel;
use app\api\model\MeetTopicModel;
use app\api\model\MeetTypeModel;

use app\api\model\MeetUserModel;
use app\api\model\room\RoomModel;
use app\api\model\room\RoomOrderModel;
use app\api\service\Format;
use app\common\controller\Api;
use think\Config;
use think\Db;

class Meet extends Api
{
// 无需登录的接口,*表示全部
    protected $noNeedLogin = ['cate'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    // 列表
    public function lists()
    {
        $limit = input('limit') ? input('limit') : '15';
        $map = [];
        //默认党支部会议
        $map['type'] = input('type')?input('type'):1;
        if (!empty(input('status'))) {
            $map['status'] = input('status');
        }
        if (!empty(input('user_id'))) {
            $map['user_id'] = input('user_id');
        }
        $list = MeetModel::where($map)->whereNull('deletetime')
            ->paginate($limit)
            ->toArray();
        $this->success('成功', $list);
    }

   // 草稿列表
    public function draft()
    {
        $limit = input('limit') ? input('limit') : '15';
        $map = [];
        //默认党支部会议
        $map['type'] = input('type')?input('type'):1;
        $map['status'] = 0;
        $map['user_id'] = $this->auth->id;

        $list = MeetModel::where($map)->whereNull('deletetime')
            ->field("id,issued_ids,check_room_ids,attend_meet_ids,attend_topic_ids,check_ids,type_id,user_id,room_id,title,status,content,start_time,end_time")
            ->order("id desc")
            ->paginate($limit)->each(function ($item, $key) use (&$map) {
                $item['action'] = MeetModel::getActionName($item,$this->auth->id);
                $room = RoomModel::where( "id", "in",$item['room_id']  )->field("id,title,floor,people")->find();
                $item['room'] = $room;
                $item['user'] =  MeetUserModel::where( "id", "in",$item['user_id']  )->field("id,nickname,username,avatar")->find();
                $item['status_name'] = getStatusName($item['status'],$item['start_time']);

                $item['type_name'] = getTypeName($item['type_id']);
                $item['time']  =  date("m月d日", strtotime($item['start_time'])) ."  ". getWeekName($item['start_time']) ."  ".date("H:i", strtotime($item['start_time']))."-". date("H:i", strtotime($item['end_time']));


                unset($item['type_id'] );
                unset($item['room_id'] );
                return $item;
            })
            ->toArray();
        $this->success('成功', $list);
    }

    // 我的列表发布的
    public function lists_mine()
    {
        $limit = input('limit') ? input('limit') : '15';
        $meet_type = input('meet_type') == 1?1:0;
        $map = [];
        if (!empty(input('status'))) {
            $map['status'] = input('status');
        }
         $map['user_id'] =$this->auth->id;
        $list = MeetModel::where($map)->whereNull('deletetime')
            ->where('meet_type',$meet_type)
            ->field("*")
            ->order("id desc")
            ->paginate($limit)->each(function ($item, $key) use (&$map) {
                $item['action'] = MeetModel::getActionName($item,$this->auth->id);
                $room =  RoomModel::where( "id", "in",$item['room_id']  )->field("id,title,floor,people")->find();
                $item['room'] = $room?$room:[];
                $item['user'] =  MeetUserModel::where( "id", "in",$item['user_id']  )->field("id,nickname,username,avatar")->find();
                $item['status_name'] = getStatusName($item['status'],$item['start_time']);

                $item['type_name'] = getTypeName($item['type_id']);
                $item['time']  =  date("m月d日", strtotime($item['start_time'])) ."  ". getWeekName($item['start_time']) ."  ".date("H:i", strtotime($item['start_time']))."-". date("H:i", strtotime($item['end_time']));


                unset($item['files'] );

                unset($item['createtime'] );
                unset($item['updatetime'] );
                unset($item['deletetime'] );
                unset($item['subtitle'] );
                unset($item['weigh'] );
                unset($item['image'] );
                unset($item['images'] );
                unset($item['params'] );
                unset($item['views'] );
                unset($item['late_time'] );
                unset($item['normal_time'] );
                unset($item['normal_tip'] );
                unset($item['late_time'] );
                unset($item['late_tip'] );
                unset($item['absence_tip'] );
                unset($item['type_id'] );
                unset($item['room_id'] );
                return $item;
            })
            ->toArray();
        $user = $this->auth->getUserinfo();
        $list['is_config'] = $user['is_config'];
        $this->success('成功', $list);
    }


    // 已经结束的会议
    public function lists_attend()
    {
        $limit = input('limit') ? input('limit') : '15';
        $map = [];
        /*if (!empty(input('status'))) {
            $map['status'] = input('status');
        }else{

        }*/
        $map['status'] = ['in' , [9]];
        $meet_type = input('meet_type') == 1?1:0;

        $list = MeetModel::where($map)
            ->field("*")
            ->where('meet_type',$meet_type)
            ->where('find_in_set(' . $this->auth->id. ',user_id) 
            or find_in_set(' . $this->auth->id. ',issued_ids) 
            or find_in_set(' . $this->auth->id. ',attend_meet_ids) 
            or find_in_set(' . $this->auth->id. ',attend_topic_ids) 
            or find_in_set(' . $this->auth->id. ',check_ids) ' )
            ->whereNull('deletetime')
            ->order("id desc")
            ->paginate($limit)->each(function ($item, $key) use (&$map) {
                $item['action'] = MeetModel::getActionName($item,$this->auth->id);
                $room =  RoomModel::where( "id", $item['room_id']  )->field("id,title,floor,people")->find();
                $item['room'] = $room?$room:[];
                $item['user'] = MeetUserModel::getUser($item['user_id']);
                $item['status_name'] = getStatusName($item['status'],$item['start_time']);

                $item['type_name'] = getTypeName($item['type_id']);
                $item['time']  =  date("m月d日", strtotime($item['start_time'])) ."  ". getWeekName($item['start_time']) ."  ".date("H:i", strtotime($item['start_time']))."-". date("H:i", strtotime($item['end_time']));


                unset($item['files'] );

                unset($item['createtime'] );
                unset($item['updatetime'] );
                unset($item['deletetime'] );
                unset($item['subtitle'] );
                unset($item['weigh'] );
                unset($item['image'] );
                unset($item['images'] );
                unset($item['params'] );
                unset($item['views'] );
                unset($item['late_time'] );
                unset($item['normal_time'] );
                unset($item['normal_tip'] );
                unset($item['late_time'] );
                unset($item['late_tip'] );
                unset($item['absence_tip'] );
                unset($item['type_id'] );
                unset($item['room_id'] );
                return $item;
            })
            ->toArray();
        $user = $this->auth->getUserinfo();
        $list['is_config'] = $user['is_config'];
        $this->success('成功', $list);
    }


    // 即将开始会议
    public function lists_about()
    {
        $limit = input('limit') ? input('limit') : '15';
        $map = [];
        if (!empty(input('status'))) {
            $map['status'] = input('status');
        }else{
            $map['status'] = ['in' , [1,8]];
        }
        $meet_type = input('meet_type') == 1?1:0;

      /*  'find_in_set(' . $this->auth->id. ',check_room_ids)
        or find_in_set(' . $this->auth->id. ',check_ids)
          or find_in_set(' . $this->auth->id. ',attend_meet_ids)
          or find_in_set(' . $this->auth->id. ',attend_topic_ids) '*/
        $list = MeetModel::where($map)->where(
            'find_in_set(' . $this->auth->id. ',user_id) 
            or find_in_set(' . $this->auth->id. ',issued_ids) 
            or find_in_set(' . $this->auth->id. ',attend_meet_ids) 
            or find_in_set(' . $this->auth->id. ',attend_topic_ids) 
            or find_in_set(' . $this->auth->id. ',topic_collector_id) 
            or find_in_set(' . $this->auth->id. ',check_ids) ' )
            ->where('meet_type',$meet_type)
            //->whereOr('topic_collector_id',$this->auth->id)
            ->whereNull('deletetime')
            ->field("*")
            ->order("id desc")
            ->paginate($limit)->each(function ($item, $key) use (&$map) {
                $item['action'] = MeetModel::getActionName($item,$this->auth->id);
                $room = RoomModel::where( "id", "in",$item['room_id']  )->field("id,title,floor,people")->find();
                $item['room'] = $room;
                $item['user'] = MeetUserModel::getUser($item['user_id']);
                $item['status_name'] = getStatusName($item['status'],$item['start_time']);

                $item['type_name'] = getTypeName($item['type_id']);
                $item['time']  =  date("m月d日", strtotime($item['start_time'])) ."  ". getWeekName($item['start_time']) ."  ".date("H:i", strtotime($item['start_time']))."-". date("H:i", strtotime($item['end_time']));
                $map = [
                    'meet_id' => $item['id'],
                    'user_id' => $this->auth->id,
                ];
                $topic = MeetTopicModel::where($map)->find();
                $item['is_topic'] = $topic?1:0;
                unset($item['files'] );

                unset($item['createtime'] );
                unset($item['updatetime'] );
                unset($item['deletetime'] );
                unset($item['subtitle'] );
                unset($item['weigh'] );
                unset($item['image'] );
                unset($item['images'] );
                unset($item['params'] );
                unset($item['views'] );
                unset($item['late_time'] );
                unset($item['normal_time'] );
                unset($item['normal_tip'] );
                unset($item['late_time'] );
                unset($item['late_tip'] );
                unset($item['absence_tip'] );
                unset($item['type_id'] );
                unset($item['room_id'] );
                return $item;
            })
            ->toArray();
        $user = $this->auth->getUserinfo();
        $list['is_config'] = $user['is_config'];
        $this->success('成功', $list);
    }


    // 详情
    public function detail()
    {
        $id = input('id');
        $info = MeetModel::detail(['id'=>$id,'user_id'=> $this->auth->id]);
        if ($info['status'] == 1) {
            $this->success($info['msg'], $info['data']);
        } else {
            $this->error( $info['msg'],$info);
        }
    }



    // 克隆
    public function clone()
    {
        $id = input('id');
        $input = MeetModel::get($id)->toArray();
        unset($input['id']);
        unset($input['start_time']);
        unset($input['end_time']);
        unset($input['files']);
        $input['is_jiyao'] = 0;
        $input['is_yiti'] = 0;
        $input['user_id'] = $this->auth->id;
        $input['status'] = 0;
        $model = new MeetModel($input);
        $row = $model->allowField(true)->save();
        $this->success('克隆成功', $row);
    }

    //检查是否暂用
    public function check_room()
    {
        $user = $this->auth->getUser();
        $input = input();
        $input['user_id'] = $this->auth->id;

        $info = MeetModel::checkTime(['room_id' => $input["room_id"],'start_time' => $input["start_time"],'end_time' => $input["end_time"],]);

      if ($info['status'] == 1) {
          $this->success($info['msg'], $info);
        } else {
            $this->error( $info['msg'],$info);
        }
    }

    //添加
    public function add()
    {
        $user = $this->auth->getUser();
        $input = input();
        $input['user_id'] = $this->auth->id;
        $input['nickname'] = $user['nickname'];
        $input['meet_type'] = empty($input['meet_type'])?0:1;
        $type_id = input('type_id');
        $type = MeetTypeModel::get($type_id);
        //0 草稿
        if (  isset($input['status'] ) && $input['status'] == 0) {
            $input['status'] = 0;
        }else{
            $input['status'] = 2;
        }
        if($input['status'] != 0) {

            if ($input['type_id'] == 1) {
                if (empty($input['topic_submit_off_time'])) {
                    $this->error('请填写议题截止时间');
                }
                if (empty($input['topic_collector_id'])) {
                    $this->error('请填写议题收集人');
                }
            }

            if (isset($input['topic_submit_off_time'])) {
                $input['topic_submit_off_time'] = strtotime($input['topic_submit_off_time']);
            }

            if (empty($input['title'])) {
                $this->error('请填写会议名称');
            }
            if (empty($input['room_id'])) {
                $this->error('请选择会议室');
            }
            if (empty($input['content'])) {
                $this->error('请填写会议内容');
            }
            if (empty($input['start_time'])) {
                $this->error('请填写会议时间');
            }
            if (empty($input['end_time'])) {
                $this->error('请填写会议结束时间');
            }
            /*if (empty($input['sign_way'])) {
                $this->error('请选择签到方式');
            }*/
           /* if (!empty($input['have_goods'])) {
                if (empty($input['goods_name'])) {
                    $this->error('请填写领取物品');
                }
            }*/
            if (empty($input['attend_meet_ids'])) {
                $this->error('请选择参会人员');
            }
            if($type['type'] == 1){
                if (empty($input['attend_topic_ids'])) {
                    $this->error('请选择议题人员');
                }
            }
            if((int)input('sign_way') > 0){
                if (empty($input['normal_time'])) {
                    $this->error('请填写签到时段');
                }
                $normal_time = explode("-", $input['normal_time']);
                if (count($normal_time) == 2) {
                    if (strtotime($normal_time[1]) < strtotime($normal_time[0])) {
                        $this->error('签到时段不对');
                    }
                } else {
                    $this->error('迟到时段格式不对');
                }
                if (empty($input['late_time'])) {
                    $this->error('请填写迟到时段');
                }
                $late_time = explode("-", $input['late_time']);
                if (count($late_time) == 2) {
                    if (strtotime($late_time[1]) < strtotime($late_time[0])) {
                        $this->error('迟到时段不对');
                    }
                } else {
                    $this->error('迟到时段格式不对');
                }
            }
            if (!empty($input['files'])) {
                $input['files'] = htmlspecialchars_decode($input['files']);
            }
            /*$checkFile = getCheckFiles(input('files'));
            if (empty($checkFile['status'])) {
                $this->error($checkFile['msg']);
            }*/
        }
        if (!$type) {
            $this->error('会议类型不存在');
        }
        if (!empty($type['check_ids'])) {
            $input['check_ids'] = $type['check_ids']; //替换为校长审核字段
        }
        if(is_array($input['attend_meet_ids'])){
            $input['attend_meet_ids'] = implode(',',$input['attend_meet_ids']);
        }
        if(is_array($input['attend_topic_ids'])){
            $input['attend_topic_ids'] = implode(',',$input['attend_topic_ids']);
        }
        $input['attend_meet_ids'] = Format::formatInput($input['attend_meet_ids']);
        $input['attend_meet_ids'] = Format::getUserByWxid($input['attend_meet_ids']);

        $input['attend_topic_ids'] = Format::formatInput($input['attend_topic_ids']);
        $input['attend_topic_ids'] = Format::getUserByWxid($input['attend_topic_ids']);

        $room = Db::table('fa_mrbs_room')->where('id',$input['room_id'])->find();

        //获取会议室审核人
        $input['check_room_ids'] = $room?$room['manager_id']:'';
        if(empty($room['manager_id'])){
            $input['status'] = 1;
        }
        $info = MeetModel::checkTime(['room_id' => $input["room_id"], 'start_time' => $input["start_time"], 'end_time' => $input["end_time"],]);
        if ($info['status'] == 1) {
            //$input['check_room_ids'] = $info['data']['manager_id'];
            unset( $input['id']);
            $input['type'] = $type['type'];
            $input['deletetime'] = null;
            $input['is_yiti'] = 0;
            $input['is_jiyao'] = 0;
            $model =  new MeetModel($input);
            $row = $model->allowField(true)->save();
            if($input['status'] == 2){
                $meet_id = $model->getLastInsID();
                $input['meet_id'] = $meet_id;
                //给另一张表增加数据
                $info = RoomOrderModel::saveData($input);
                $info = MeetNoticeModel::sendMeetNotice($input,"room_order",[]);
            }
            $this->success('添加成功', $row);
        } else {
            $this->error( $info['msg'],$info);
        }
    }


    /*
     * 重新提交
     * */
    public function edit()
    {
        $input = input();
        $input["user_id"] = $this->auth->id;
        unset($input['deletetime']);
       /* $list = \app\common\model\User::where('wx_userid','in',explode(',',$input['attend_meet_ids']))->column('id');
        if(!empty($list)){
            $input['attend_meet_ids'] = implode(',',$list);
        }
        $list = \app\common\model\User::where('wx_userid','in',explode(',',$input['attend_topic_ids']))->column('id');
        if(!empty($list)){
            $input['attend_topic_ids'] = implode(',',$list);
        }*/
        if(is_array($input['attend_meet_ids'])){
            $input['attend_meet_ids'] = implode(',',$input['attend_meet_ids']);
        }
        if(is_array($input['attend_topic_ids'])){
            $input['attend_topic_ids'] = implode(',',$input['attend_topic_ids']);
        }
        $input['attend_meet_ids'] = Format::formatInput($input['attend_meet_ids']);
        $input['attend_meet_ids'] = Format::getUserByWxid($input['attend_meet_ids']);
        $input['attend_topic_ids'] = Format::formatInput($input['attend_topic_ids']);
        $input['attend_topic_ids'] = Format::getUserByWxid($input['attend_topic_ids']);
        $info = MeetModel::edit($input);
        if ($info['status'] == 1) {
            $this->success($info['msg']);
        } else {
            $this->error($info['msg']);
        }
    }

    /*
     * 修改基本的三项信息
     * */
    public function edit_info()
    {
        $input = input();
        $input["user_id"] = $this->auth->id;
        $data = ['room_id' => $input["room_id"],'start_time' => $input["start_time"],'id' => $input["id"],'user_id' => $input["user_id"],];
        $info = MeetModel::edit($data);
        if ($info['status'] == 1) {
            $this->success(  $info['msg']);
        } else {
            $this->error(  $info['msg']);
        }
    }


    public function edit_status()
    {
        $input = input();
        $input["user_id"] = $this->auth->id;
        $model = MeetModel::get( $input['id']);
        if (in_array($input["status"], [-1, 2,3,9,8,0])) {
            $data = ['status' => $input["status"] ,'id' => $input["id"],'user_id' => $input["user_id"]];
            $info = MeetModel::edit_status($data);
            if ($info['status'] == 1) {
                $this->success(  '操作成功');
            } else {
                $this->error(  $info['msg']);
            }
        }  else  {
            $this->error('修改状态不对');
        }
    }

    public function delete()
    {
        $input = input();
        $model = new MeetModel();
        // $row = $model->where(['id' => $input['id'],'user_id' =>  $this->auth->id])->delete();
        $row = MeetModel::destroy($input['id']);
        if ($row) {
            $this->success('删除成功', $row);
        } else {
            $this->error('删除失败');
        }
    }

    public function cancelMeet()
    {
        $input = input();
        if(empty($input['id'])){
             $this->error('会议ID必传');
        }
        if(empty($input['cancel_reason'])){
             $this->error('请输入取消原因');
        }
        $model = new MeetModel();
        $row = $model->where([
            'id' => $input['id'],
           // 'user_id' =>  $this->auth->id
            ])
            ->find();
        if ($row) {
            $row->status = -1;
            $row->cancel_reason = $input['cancel_reason'];
            $row->save();
            $info = MeetNoticeModel::sendMeetNotice($row,"meet_delete",[]);
            $this->success('取消成功', $row);
        }
        $this->success('取消成功', $row);
    }


    public function types()
    {
        $input = input();
        $list = MeetTypeModel::where("1=1")->group("type")->select();

        $this->success('成功', $list);
    }

    //初始化数据
    public function form()
    {
        $user = $this->auth->getUser();
        $input = input();
        if (empty($input['id'])) {
            $this->error('请选择会议类型');
        }
        $room_id = input('room_id');
        if(empty($room_id)){
             $this->error('会议室room_id必传');
        }
        $room = $room = Db::table('fa_mrbs_room')->where('id',$input['room_id'])->find();
        $roomuser = $room?$room['manager_id']:'';

        $val = MeetTypeModel::where(" id =". $input['id'])->group("type")->find();
        $val['user'] =  MeetUserModel::where( "id", "in",$this->auth->id  )->field("id,nickname,username,avatar")->find();
        if($val['type'] == 2){
            $val['type'] = 1;
        }
        //‘清外活动’前端模板修改为‘其它’
        if($val['type'] == 6){
            $val['type'] = 5;
        }
        $val['check_ids'] = $val['check_ids'];  //返回管理员审核的用户
        $val['check_ids_user'] =  MeetUserModel::where( "id", "in",$val['check_ids']  )
            ->field("id,wx_userid,nickname,username,avatar")
            ->select();

        $val['shouji_ids_user'] = MeetUserModel::where("id", "in", $val['shouji_ids'])->field("id,wx_userid,nickname,username,avatar")->select();

            $val['attend_meet_ids_user'] =  MeetUserModel::where( "id", "in",$val['attend_meet_ids']  )->field("id,wx_userid,nickname,username,avatar")->select();
             $attend_meet_wx_ids = array_column($val['attend_meet_ids_user'],'wx_userid');
             $val['attend_meet_wx_ids'] = implode(',',$attend_meet_wx_ids);

            $val['attend_topic_ids_user'] =  MeetUserModel::where( "id", "in",$val['attend_topic_ids']  )->field("id,wx_userid,nickname,username,avatar")->select();
           $attend_topic_wx_ids = array_column($val['attend_topic_ids_user'],'wx_userid');
           $val['attend_topic_wx_ids'] =  implode(',',$attend_topic_wx_ids);

            $val['approver_ids_user'] =  MeetUserModel::where( "id", "in",$roomuser  )->field("id,nickname,username,avatar")->select();
            $issued_ids_user = MeetUserModel::where( "id", "in",$val['issued_ids']  )->field("id,nickname,username,avatar")->select();
            if(empty($issued_ids_user)){
                $issued_ids_user = [
                    [
                        'id' => $user['id'],
                        'nickname' => $user['nickname'],
                        'username' => $user['username'],
                        'avatar' => $user['avatar'],]
                     ];
            }
            $val['issued_ids_user'] =  $issued_ids_user;

        $data['info'] = $val;
        $data['user'] = $user;
        $data['sign_way'] = [  [  "id"  =>'1',"txt"  =>'页面签到'],[  "id"  =>'2',"txt"  =>'二维码签到'],];
        $data['have_goods'] = [  [  "id"  =>'0',"txt"  =>'无'],[  "id"  =>'1',"txt"  =>'有'],];
        $data['tip'] =  Config::get('site.meet_sign_tip') ;
        $data['tip'] = json_decode($data['tip'], true);
        $this->success('成功', $data);
    }

    //初始化数据
    public function formAll()
    {
        $input = input();
        $list = MeetTypeModel::where("1=1")->group("type")->select();
        foreach ($list as $k => &$val) {
            $val['check_ids_user'] =  MeetUserModel::where( "id", "in",$val['check_ids']  )->field("id,nickname,username,avatar")->select();
            $val['attend_meet_ids_user'] =  MeetUserModel::where( "id", "in",$val['attend_meet_ids']  )->field("id,nickname,username,avatar")->select();
            $val['attend_topic_ids_user'] =  MeetUserModel::where( "id", "in",$val['attend_topic_ids']  )->field("id,nickname,username,avatar")->select();
            $val['approver_ids_user'] =  MeetUserModel::where( "id", "in",$val['approver_ids']  )->field("id,nickname,username,avatar")->select();
            $val['issued_ids_user'] =  MeetUserModel::where( "id", "in",$val['issued_ids']  )->field("id,nickname,username,avatar")->select();
        }
        $data['typelist'] = $list ;
        $data['tip'] = [   "late_time"  =>'12:10',
            "normal_time"  =>'12:10',
            "normal_tip"  =>'正常提示语',
            "late_tip"  =>'迟到提示语',
            "absence_tip" => '缺勤提示',] ;
        $this->success('成功', $data);
    }
}
